<?php
class Conf{
	private $file;
	private $xml;
	private $lastmatch;

	function __construct($file){
		$this->file = $file;
		if(!file_exists($file)){
			throw new Exception("file '$file' dose not exist");
		}
		
		$this->xml = simplexml_load_file($file);
		var_dump($this->xml);
	}

	//将新的配置数据保存到文件中
	function write(){
		if(! is_writable($this->file)){
			throw new Exception("file '{$this->file}' is not writeable");
		}
		file_put_contents($this->file,$this->xml->asXML());
	}

	//使用XPath和给定的name属性来定位item元素，并返回值
	function get($str){
		$matches = $this->xml->xpath("/conf/item[@name=\"$str\"]");
		if(count($matches)){
			$this->lastmatch = $matches[0];
			return (string)$matches[0];
		}
		return null;
	}

	//改变已存在项的值或创建一个新项
	function set($key,$value){
		if(!is_null($this->get($key))){
			$this->lastmatch[0] = $value;
			return ;
		}
		$conf = $this->xml->conf;
		$this->xml->addChild('item',$value)->addAttribute('name',$key);
	}
}


try{
	//echo dirname(__FILE__)."/test.xml";
	$conf = new Conf(dirname(__FILE__)."/test.xml");
	print "user: ".$conf->get('user')."</BR>";
	print "host: ".$conf->get('host')."</BR>";
	$conf->set("pass","newpass--");
	$conf->write();

}catch(Exception $e){
	die($e->__toString());
}